// Storage utilities for Chrome storage API
class StorageManager {
  static async initialize() {
    const data = await chrome.storage.local.get([
      'favorites',
      'userContent',
      'reminders',
      'settings',
      'initialized'
    ]);

    // Initialize default data if first run
    if (!data.initialized) {
      const defaultReminders = await this.loadDefaultReminders();
      await chrome.storage.local.set({
        favorites: [],
        userContent: [],
        reminders: defaultReminders,
        settings: {
          notificationsEnabled: true,
          badgeEnabled: true,
          theme: 'light',
          notificationSound: 'beep'
        },
        initialized: true
      });
    }

    return data;
  }

  static async loadDefaultReminders() {
    // Default reminders will be loaded from data/default-reminders.js via script tag in HTML
    // Return empty array here - actual loading happens in HTML files
    return [];
  }

  static async getFavorites() {
    const data = await chrome.storage.local.get('favorites');
    return data.favorites || [];
  }

  static async addFavorite(id) {
    const favorites = await this.getFavorites();
    if (!favorites.includes(id)) {
      favorites.push(id);
      await chrome.storage.local.set({ favorites });
    }
  }

  static async removeFavorite(id) {
    const favorites = await this.getFavorites();
    const filtered = favorites.filter(fav => fav !== id);
    await chrome.storage.local.set({ favorites: filtered });
  }

  static async isFavorite(id) {
    const favorites = await this.getFavorites();
    return favorites.includes(id);
  }

  static async getUserContent() {
    const data = await chrome.storage.local.get('userContent');
    return data.userContent || [];
  }

  static async addUserContent(content) {
    const userContent = await this.getUserContent();
    const newContent = {
      id: `user-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      title: content.title,
      link: content.link || '',
      description: content.description || '',
      timestamp: Date.now(),
      category: content.category || 'Custom',
      tags: content.tags || []
    };
    userContent.push(newContent);
    await chrome.storage.local.set({ userContent });
    return newContent;
  }

  static async removeUserContent(id) {
    const userContent = await this.getUserContent();
    const filtered = userContent.filter(item => item.id !== id);
    await chrome.storage.local.set({ userContent: filtered });
  }

  static async getReminders() {
    const data = await chrome.storage.local.get('reminders');
    return data.reminders || [];
  }

  static async updateReminder(reminderId, updates) {
    const reminders = await this.getReminders();
    const index = reminders.findIndex(r => r.id === reminderId);
    if (index !== -1) {
      reminders[index] = { ...reminders[index], ...updates };
      await chrome.storage.local.set({ reminders });
      return reminders[index];
    }
    return null;
  }

  static async addCustomReminder(reminder) {
    const reminders = await this.getReminders();
    const newReminder = {
      id: `custom-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      title: reminder.title,
      description: reminder.description || '',
      frequency: reminder.frequency || 60,
      enabled: reminder.enabled !== undefined ? reminder.enabled : true,
      custom: true,
      icon: reminder.icon || '⏰',
      category: reminder.category || 'Custom',
      timeOfDay: reminder.timeOfDay || null,
      lastTriggered: null
    };
    reminders.push(newReminder);
    await chrome.storage.local.set({ reminders });
    return newReminder;
  }

  static async removeReminder(reminderId) {
    const reminders = await this.getReminders();
    const filtered = reminders.filter(r => r.id !== reminderId);
    await chrome.storage.local.set({ reminders: filtered });
  }

  static async getSettings() {
    const data = await chrome.storage.local.get('settings');
    return data.settings || {
      notificationsEnabled: true,
      badgeEnabled: true,
      theme: 'light',
      notificationSound: 'beep'
    };
  }

  static async updateSettings(updates) {
    const settings = await this.getSettings();
    const newSettings = { ...settings, ...updates };
    await chrome.storage.local.set({ settings: newSettings });
    return newSettings;
  }

  // Gamification methods
  static async getGamificationData() {
    const data = await chrome.storage.local.get('gamification');
    return data.gamification || {
      xp: 0,
      level: 1,
      totalXP: 0,
      currentStreak: 0,
      longestStreak: 0,
      lastActiveDate: null,
      completedGoals: {},
      unlockedAchievements: [],
      goalProgress: {},
      stats: {
        goalsCompleted: 0,
        articlesRead: 0,
        hydrationCompleted: 0,
        remindersCompleted: 0
      }
    };
  }

  static async updateGamificationData(updates) {
    const gamification = await this.getGamificationData();
    const newData = { ...gamification, ...updates };
    await chrome.storage.local.set({ gamification: newData });
    return newData;
  }

  static async addXP(amount) {
    const data = await this.getGamificationData();
    const newXP = data.totalXP + amount;
    const newLevel = this.calculateLevel(newXP);
    const leveledUp = newLevel > data.level;
    
    await this.updateGamificationData({
      xp: data.xp + amount,
      totalXP: newXP,
      level: newLevel
    });

    return { leveledUp, newLevel, newXP };
  }

  static calculateLevel(totalXP) {
    if (totalXP <= 0) return 1;
    
    let level = 1;
    let accumulatedXP = 0;
    
    while (accumulatedXP <= totalXP) {
      const xpForThisLevel = Math.floor(100 * Math.pow(level, 1.5));
      accumulatedXP += xpForThisLevel;
      if (accumulatedXP <= totalXP) {
        level++;
      } else {
        break;
      }
    }
    
    return level;
  }

  static async updateStreak() {
    const data = await this.getGamificationData();
    const today = new Date().toDateString();
    const yesterday = new Date(Date.now() - 86400000).toDateString();
    
    if (data.lastActiveDate === today) {
      return data.currentStreak; // Already updated today
    }

    let newStreak = 1;
    if (data.lastActiveDate === yesterday) {
      newStreak = data.currentStreak + 1;
    }

    const longestStreak = Math.max(newStreak, data.longestStreak || 0);

    await this.updateGamificationData({
      currentStreak: newStreak,
      longestStreak: longestStreak,
      lastActiveDate: today
    });

    return newStreak;
  }

  static async updateGoalProgress(goalId, progress) {
    const data = await this.getGamificationData();
    const currentProgress = data.goalProgress[goalId] || 0;
    const newProgress = currentProgress + progress;
    
    await this.updateGamificationData({
      goalProgress: {
        ...data.goalProgress,
        [goalId]: newProgress
      }
    });

    return newProgress;
  }

  static async completeGoal(goalId, xpReward) {
    const data = await this.getGamificationData();
    const completedGoals = data.completedGoals || {};
    const today = new Date().toDateString();
    
    if (!completedGoals[goalId]) {
      completedGoals[goalId] = [];
    }
    
    if (!completedGoals[goalId].includes(today)) {
      completedGoals[goalId].push(today);
      await this.updateGamificationData({
        completedGoals: completedGoals,
        stats: {
          ...data.stats,
          goalsCompleted: (data.stats.goalsCompleted || 0) + 1
        }
      });
      
      const { leveledUp, newLevel } = await this.addXP(xpReward);
      return { leveledUp, newLevel, xpReward };
    }
    
    return { leveledUp: false, newLevel: data.level, xpReward: 0 };
  }

  static async unlockAchievement(achievementId) {
    const data = await this.getGamificationData();
    if (data.unlockedAchievements.includes(achievementId)) {
      return false; // Already unlocked
    }

    const unlocked = [...data.unlockedAchievements, achievementId];
    await this.updateGamificationData({
      unlockedAchievements: unlocked
    });

    return true;
  }

  static async getGoals() {
    const data = await chrome.storage.local.get('userGoals');
    return data.userGoals || [];
  }

  static async addGoal(goal) {
    const goals = await this.getGoals();
    const newGoal = {
      id: `goal-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      ...goal,
      createdAt: Date.now()
    };
    goals.push(newGoal);
    await chrome.storage.local.set({ userGoals: goals });
    return newGoal;
  }

  static async removeGoal(goalId) {
    const goals = await this.getGoals();
    const filtered = goals.filter(g => g.id !== goalId);
    await chrome.storage.local.set({ userGoals: filtered });
  }

  static async updateGoal(goalId, updates) {
    const goals = await this.getGoals();
    const index = goals.findIndex(g => g.id === goalId);
    if (index !== -1) {
      goals[index] = { ...goals[index], ...updates };
      await chrome.storage.local.set({ userGoals: goals });
      return goals[index];
    }
    return null;
  }

  // Background noise settings
  static async getNoiseSettings() {
    const data = await chrome.storage.local.get('noiseSettings');
    return data.noiseSettings || {
      volume: 0.5,
      playing: null
    };
  }

  static async updateNoiseSettings(updates) {
    const settings = await this.getNoiseSettings();
    const newSettings = { ...settings, ...updates };
    await chrome.storage.local.set({ noiseSettings: newSettings });
    return newSettings;
  }

  // RSS Feed methods
  static async getRSSArticles() {
    const data = await chrome.storage.local.get('rssArticles');
    return data.rssArticles || [];
  }

  static async getRSSLastUpdate() {
    const data = await chrome.storage.local.get('rssLastUpdate');
    return data.rssLastUpdate || null;
  }

  static async refreshRSSFeed() {
    return new Promise((resolve, reject) => {
      chrome.runtime.sendMessage({ action: 'fetchRSS' }, (response) => {
        if (chrome.runtime.lastError) {
          reject(new Error(chrome.runtime.lastError.message));
        } else if (response && response.success) {
          resolve(response);
        } else {
          reject(new Error(response?.error || 'Failed to fetch RSS feed'));
        }
      });
    });
  }
}

